<?php

namespace app\common\service;

use app\common\model\Admin;
use app\common\model\Admin as Model;
use app\common\util\LogHelper;
use app\common\util\Result;
use app\common\util\WhereBuilder;
use think\facade\Validate;

/**
 * 管理员 业务类
 */
class AdminService extends Service
{
    protected string $model_name = 'admin';
    protected string $model_cname = '管理员';

    public function detail($param): Result
    {
        $params = $this->autoMergeParams($param);
        $id = getValueFromArray("id", $params);
        if (!$id) {
            return Result::error("ID 不能为空");
        }
        $model = Admin::with(["admin_role", "admin_post"])->append(["valid_text", "is_pass_text"])->find($id);
        if (!$model) {
            return Result::error("数据不存在");
        }
        return Result::success($model);
    }

    /**
     * 管理员分页
     */
    public function adminPage($param = [])
    {
        $this->autoParams($param);
        $param = $this->autoMergeParams($param);

        $keyword = $this->pg('keyword');

        /*$where = WhereBuilder::builder()
            ->like('login_name|real_name|phone', $keyword)
            ->build();*/

        $where = [];
        if ($keyword) {
            $where[] = ["login_name|real_name|phone", "like", "%$keyword%"];
        }

        $status = getValueFromArray("status", $param);

        if ($status !== "") {
            $where[] = ["is_pass", "=", $status];
        }
//        print_r($where);

        return (new Model)->with([
            'admin_role' => function ($query) {
                $query->field(['id', 'name']);
            },
            'admin_post' => function ($query) {
                $query->field(['id', 'name']);
            },
        ])
            ->where($where)
            ->order('id desc')
            ->hidden(['password'])
            ->append(["valid_text", "is_pass_text"])
            ->paginate($this->tp6Page());
    }

    /**
     * 创建
     * @param $param
     * @return Model|\think\Model
     */
    public function create($param = [])
    {
        $param = $this->autoParams($param);
        $data = $param[$this->model_name];

        $this->validate($data, Validate::rule([
            'login_name|账号' => 'require|min:3|max:50',
            'real_name|真实姓名' => 'require',
            'password|密码' => 'require|max:50',
            'phone|联系电话' => 'require',
            'role_id|角色id' => 'require',
            'valid|有效性' => 'require',
        ]));

        //检查手机号有没有被使用
        $wherePhone = [];
        $wherePhone[] = ["phone", "=", $data["phone"]];
        $count = Admin::where($wherePhone)->count();
        if ($count) {
            //如果大于0，表示手机号被使用了
            throw $this->exception('手机号被使用');
        }

        if (Model::where('login_name', $data['login_name'])->find()) {
            throw $this->exception('账号重复');
        }

        $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);

        //添加
        $model = Model::create($data);
        $model->hidden(['password']);

        //日志记录
        LogHelper::logAdmin($model, '创建' . $this->model_cname);

        return $model;
    }

    /**
     * 更新
     * @param $param
     * @return Model
     * @throws \Exception
     */
    public function update($param = [])
    {
        $param = $this->autoParams($param);
        $data = $param[$this->model_name];

        $this->validate($data, Validate::rule([
            'id' => 'require',
            'login_name|账号' => 'require|min:3|max:50',
            'real_name|真实姓名' => 'require',
            'phone|联系电话' => 'require',
            'role_id|角色id' => 'require',
            'valid|有效性' => 'require',
        ]));

        //检查手机号有没有被使用
        $wherePhone = [];
        $wherePhone[] = ["id", "<>", $data["id"]];
        $wherePhone[] = ["phone", "=", $data["phone"]];
        $count = Admin::where($wherePhone)->count();
        if ($count) {
            //如果大于0，表示手机号被使用了
            throw $this->exception('手机号被使用');
        }
        if (Model::where('login_name', $data['login_name'])->where('id', '<>', $data['id'])->find()) {
            throw $this->exception('账号重复');
        }

        unset($data['password']);

        // 检查是否存在
        $model = Model::findOrEmpty($data['id']);
        if ($model->isEmpty()) {
            throw $this->exception($this->model_cname . '不存在');
        }

        //更新
        $model->save($data);
        $model->hidden(['password']);

        //日志记录
        LogHelper::logAdmin($model, '更新' . $this->model_cname);

        return $model;
    }

    /**
     * 删除
     * @param $param
     * @return Model|mixed
     * @throws \Exception
     */
    public function delete($param = [])
    {
        $this->autoParams($param);
        $model = $this->one(Model::class);
        $model->delete();

        //日志记录
        LogHelper::logAdmin($model, '删除' . $this->model_cname);

        return $model;
    }

    /**
     * 重置密码
     * @param $param
     * @return Model|mixed
     * @throws \Exception
     */
    public function resetPassword($param = [])
    {
        $param = $this->autoParams($param);
        $this->validate($param, Validate::rule([
            'id' => 'require',
            'password|密码' => 'require|max:50',
        ]));

        $model = $this->one(Model::class);
        $model->password = password_hash($param['password'], PASSWORD_BCRYPT);
        $model->save();
        $model->hidden(['password']);

        //日志记录
        LogHelper::logAdmin($model, '重置密码' . $this->model_cname);

        return $model;
    }
}
